<!-- 航班查询组件 -->
<template>
  <el-dialog 
    v-el-drag-dialog="{drag: true, full: false, resize: false}"
    :visible="true"
    :close-on-click-modal="false"
    @close="closeMd"
    width="500px"
  >
    <template slot="title">
      <span>{{labelTip}}查询</span>
      <span v-if="dat.jsType == 1"><i class="el-icon-sort-down"></i></span>
      <span v-else-if="dat.jsType == 2"><i class="el-icon-sort-up"></i></span>
      <span v-else></span>
    </template>
    <el-form 
      :model="fm.ps" 
      :ref="fm.fname" 
      :label-width="'auto'"
      @keyup.enter.native="onSubmit" 
    >
      <el-form-item 
        v-if="!dat.jsType"
        :label="'查询日期'"
        prop="date"
        :rules="[
          { required: true, message: '请选择查询日期', trigger: 'blur' }
        ]"
      >
        <el-date-picker
          v-model="fm.ps.date"
          type="date"
          :value-format="'yyyy-MM-dd'"
          placeholder="查询日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item 
        :label="labelTip"
        prop="num"
        :rules="[
          { required: true, message: `请输入${labelTip}`, trigger: 'blur' }
        ]"
      >
        <el-input 
          v-model="fm.ps.num" 
          :placeholder="'请输入'+labelTip"
          style="width: 180px;"
        ></el-input>&nbsp;&nbsp;
        <el-button type="primary" :disabled="fm.sb.load" @click.prevent="onSubmit">{{fm.sb.text}}</el-button>
      </el-form-item>

      <el-row>
        <el-col :span="24">
          <div class="res-list">
            <span v-if="!resDat || resDat.list.length == 0" class="c-gray">没有数据~~</span>
            <template v-else>
              <div class="res-tip" v-if="resTip">{{resTip}}</div>

              <ul class="plane-list" v-if="fm.ps.travelWay == 1">
                <li v-for="it in resDat.list" :key="it.no">
                  <div>航班号：{{it.flightNo}}</div>
                  <div 
                    :class="resObj && resObj.no == it.no ? 'c-yellow' : ''"
                  >起止机场：{{it.depPort}}{{it.depTerminal}} <i class="el-icon-right"></i> {{it.arrPort}}{{it.arrTerminal}}</div>
                  <div>起止时间：{{it.depScheduled}} - {{it.arrScheduled}}</div>
                </li>
              </ul>

              <ul class="train-list" v-else-if="fm.ps.travelWay == 2">
                <li class="title">
                  <span class="num">{{resDat.typename}}{{resDat.trainno}}</span>
                  <span class="route">{{resDat.startstation}} <i class="el-icon-right"></i> {{resDat.endstation}}</span>
                  <span class="date">{{resDat.date | time('yyyy年MM月dd号')}}</span>
                </li>

                <li>
                  <div>编号</div>
                  <div>站点</div>
                  <div>进站</div>
                  <div>发车</div>
                  <div>停留（分）</div>
                </li>
                <li v-for="(it, i) in resDat.list" 
                  :key="i" 
                  :class="resObj && resObj.no == it.no ? 'c-yellow' : ''">
                  <div>{{it.no}}</div>
                  <div>{{it.station}}</div>
                  <div>{{it.arrivaltime}}</div>
                  <div>{{it.departuretime}}</div>
                  <div>
                    <template v-if="i == 0 && it.stoptime == 0">始发</template>
                    <template v-else-if="i == resDat.list.length - 1 && it.stoptime == 0">终点</template>
                    <template v-else>{{it.stoptime}}</template>
                  </div>
                </li>
              </ul>
            </template>
          </div>
          <div style="text-align: center; padding-bottom: 10px;">
            <el-button type="danger" @click.prevent="closeMd">无{{labelTip}}</el-button>
            <el-button type="primary" @click.prevent="saveRes" v-if="dat.type && !resTip && resDat && resDat.list.length > 0">确 定</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';
import * as commonService from '@/api/services/common.service';

export default {
  name: 'FlightSearch',
  directives: { elDragDialog },
  props: [ 'dat' ],
  computed: {
    labelTip: function(){// 飞机/火车-文本标志
      if(this.dat.type == 1){
        return '航班号';
      }else if(this.dat.type == 2){
        return '车次号';
      }else{
        return '航班号/车次号';
      }
    },
    jsTip: function(){// 接/送-文本标志
      if(this.dat.jsType == 1){
        return '【接】';
      }else if(this.dat.jsType == 2){
        return '【送】';
      }else{
        return '【接/送】';
      }
    }
  },
  watch: {
    'fm.ps.num': { // 航班号输入大写，只能输入字母和数字
      handler: function(n, o){
        this.fm.ps.num = n.replace(/[\W]/g,'').toUpperCase();
      },
      deep: true
    }
  },
  data() { 
    return {
      fm: {
        fname: 'flightSearchFm',
        sb: { load: false, text: '查询' },
        ps: {
          travelWay: this.dat.type,   // 查询类型
          date: this.dat.date,        // 查询时间
          num: ''                     // 查询航班号
        }
      },
      resDat: null,                  // 航班/车次信息查询结果
      resObj: null,               // 最终匹配的站点信息
      resTip: '',                 // 查询结果提示
    }
  },
  created(){
    console.log('传入查询航班的数据', this.dat);
  },
  methods:{
    closeMd(){// 关闭弹框
      const that = this;

      that.$emit('getMdState', {state: false, name: that.dat.name, pindex: that.dat.pindex});
    },
    // 查询-数据
    onSubmit(){
      const that = this, ps = that.fm.ps;

      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) {
          return false; 
        }else{
          that.fm.sb.load = true;  // 添加按钮禁用效果
          
          let p = {...ps};
          console.log('ps2', p);
          commonService.getStationInfo(p).then(res => {
            that.fm.sb.load = false;        // 取消按钮禁用效果
            
            if(!res || res.code != 1){
              if(res.code == 0){
                that.U.qerror(`抱歉，没有查询到${that.dat.type == 1 ? '航班' : '车次'}数据`);
              }else{
                that.U.qerror(res.msg);
              }
            }else {
              that.resDat = res.data;
              that.fm.ps.travelWay = res.data.travelway;

              that.getResDat();
            }
          });
        }
      });

      return false;
    },
    // 获取-结果数据
    getResDat(){
      const that = this, ps = that.fm.ps, p = that.dat.staPoint;
      
      if(!that.resDat || that.resDat.list.length == 0) return;
      
      // 不是站点查询则返回
      if(that.dat.type == 1 || that.dat.type == 2){
        let note = p.note;            // 地点名称备注
        let list = that.resDat.list;  // 遍历的列表
        list.forEach((r, i) => {r.no = i+1;});
        if(that.dat.type == 1){// 【飞机】
          // 处理数据
          list.forEach(it => {
            it.arrScheduled = ps.date+' '+it.arrScheduled.split(' ')[1];
            it.depScheduled = ps.date+' '+it.depScheduled.split(' ')[1];
          });


          // 接：开始地点名称备注 包含 降落机场名称
          if(that.dat.jsType == 1){
            list.forEach(it => {
              if(note.indexOf(it.arrPort+it.arrTerminal) != -1) that.resObj = it;
            });

            if(!that.resObj){
              that.resTip = '抱歉，当前没有降落机场是【'+p.name+'】的航班，请核对航班号是否正确！';
            }else{
              // 保存-航班号、时间、文本
              that.resObj.flightTrainNo = that.resObj.flightNo || '';
              that.resObj.downUpTime = that.resObj.arrScheduled;

              that.resObj.infoText = `${that.resObj.flightTrainNo}降落${that.resObj.downUpTime.split(' ')[1]}`;
            }
          }else {
            // 送：结束地点名称备注 包含 起飞机场名称
            list.forEach(it => {
              if(note.indexOf(it.depPort+it.depTerminal) != -1) that.resObj = it;
            });

            if(!that.resObj){
              that.resTip = '抱歉，当前没有起飞机场是【'+p.name+'】的航班，请核对航班号是否正确！';
            }else{
              // 保存-航班号、时间、文本
              that.resObj.flightTrainNo = that.resObj.flightNo || '';
              that.resObj.downUpTime = that.resObj.depScheduled;

              that.resObj.infoText = `${that.resObj.flightTrainNo}起飞${that.resObj.downUpTime.split(' ')[1]}`;
            }
          }
        }else{// 【火车】
          // 接：开始地点名称备注 包含 进站名称
          if(that.dat.jsType == 1){
            list.forEach((it, i) => {
              // 接车站点不能是第一个站
              if(i != 0 && note.indexOf(it.station) != -1) that.resObj = it;
            });

            if(!that.resObj){
              that.resTip = '抱歉，当前没有进站是【'+p.name+'】的站点，请核对车次号是否正确！';
            }else{
              // 保存-车次号、时间、文本
              that.resObj.flightTrainNo = that.resDat.trainno;
              // let time = that.U.date2str(new Date(that.U.str2date(this.dat.date+' '+that.resObj.arrivaltime).getTime()+(1000*60*60*24*(Number(that.resObj.day) - 1))), 'yyyy-MM-dd HH:mm');
              // 此处不需要处理隔天这种情况，只要是选择日期的进站时间点对了
              let time = that.U.date2str(new Date(that.U.str2date(this.dat.date+' '+that.resObj.arrivaltime).getTime()), 'yyyy-MM-dd HH:mm');
              that.resObj.downUpTime = time;

              that.resObj.infoText = `${that.resObj.flightTrainNo}到达${that.resObj.downUpTime.split(' ')[1]}`;
            }
          }else {
            // 送：结束地点名称备注 包含 出站名称
            list.forEach((it, i) => {
              // 送车站点不能是最后一个站
              if(i != list.length - 1 && note.indexOf(it.station) != -1) that.resObj = it;
            });

            if(!that.resObj){
              that.resTip = '抱歉，当前没有出站是【'+p.name+'】的站点，请核对车次号是否正确！';
            }else{
              // 保存-车次号、时间、文本
              that.resObj.flightTrainNo = that.resDat.trainno;
              // day属性判断是否跨天，1表示没有跨天，2表示跨一天
              // let time = that.U.date2str(new Date(that.U.str2date(this.dat.date+' '+that.resObj.departuretime).getTime()+(1000*60*60*24*(Number(that.resObj.day) - 1))), 'yyyy-MM-dd HH:mm');
              // 此处不需要处理隔天这种情况，只要是选择日期的出站时间点对了
              let time = that.U.date2str(new Date(that.U.str2date(this.dat.date+' '+that.resObj.departuretime).getTime()), 'yyyy-MM-dd HH:mm');
              that.resObj.downUpTime = time;

              that.resObj.infoText = `${that.resObj.flightTrainNo}出发${that.resObj.downUpTime.split(' ')[1]}`;
            }
          }
        }
        
        // 保存接送类型
        if(that.resObj) {
          that.resTip = '';                       // 存在正确结果，则清空错误提示信息
          that.resObj.selStaName = p.name;        // 选择的站点名称
          that.resObj.type = that.dat.type;       // 站点类型
          that.resObj.jsType = that.dat.jsType;   // 接送类型
        }
      }
    },
    // 保存结果
    saveRes(){
      const that = this;
      
      if(that.resObj){
        that.$emit('getMdState', {state: false, name: that.dat.name, o: that.resObj, pindex: that.dat.pindex});
      }else{
        that.U.qerror(that.resTip);
      }
    }
    
  }
}
</script>

<style lang="less" scoped>
  .res-list{
    padding: 5px;
    border: 1px solid #efefef;
    border-radius: 5px;
    min-height: 100px;
    margin-top: 0;
    margin-bottom: 10px;

    .res-tip{
      padding: 5px 5px 5px 15px;
      margin: 0;
      // color: #ff6300;
      color: #f00;
      font-size: 13px;
    }

    ul{
      margin: 0;
      padding: 0;
    }

    .plane-list{
      li{
        list-style: none;
        padding: 10px 0 10px 5px;
        line-height: 25px;

        &:not(:last-child){
          border-bottom: 1px solid #efefef;
        }

        &:hover{
          background: #fcfafa;
        }
      }
    }

    .train-list{
      overflow-y: auto;
      max-height: 500px;

      .title{
        background: #fcfcfc;
        position: relative;

        .num{
          font-size: 13px;
          position: absolute;
          top: 5px;
          left: 0px;
        }

        .route{
          font-size: 18px;
          font-weight: 500;
          text-align: center;
          display: inline-block;
          width: 100%;
          color: #333;
        }

        .date{
          font-size: 13px;
          position: absolute;
          top: 5px;
          right: 0px;
        }

      }

      li:nth-child(n+1){
        list-style: none;
        padding: 10px 0 10px 5px;
        line-height: 10px;
        display: flex;

        div{
          flex: 1;
        }

        &:not(:last-child){
          border-bottom: 1px solid #efefef;
        }
      }
    }
  }
</style>